﻿define([
	'../libs/zepto',
	'../common/ajax',
	'../common/dialog',
	'../common/yingSoftPrg',
	'../common/yingSoftCookie',
	'../common/yingSoftPrg',
	'../common/storage',
	'../common/yingSoftSetTest'
],function(){
	
	var whole_height = window.innerHeight;
	var head_height = $('.common_header').height();
	$('.chapter_source').css('height',whole_height-head_height);
	var _gCpmArrNodes = []; //存储菜单显示的数据
	var _gCpmArrTitle = []; //存储用户选择过的标题
	var TestNum = 0; //当前章节总试题数，默认为0
	var _gCpmArrData = [];
	var _gIsVip = false;//用户是否已购买当前科目
	var clickNum = true;
	
	var value1 = G_Prg.getQueryString('m'); // m
	var value2 = G_Prg.getQueryString('n'); // n
	var _title = decodeURI(GetQueryString('title')); // title
	var hrader_title = decodeURI(GetQueryString('tit')); // tit
	var cpt = G_Prg.getQueryString('cptid');
	
	
	
	this.init = function(){
		var userID = G_Cookie.getUserID();
		if (userID){
			if(typeof(G_ChapterCache)!=='undefined'){
				_gCpmArrData = G_ChapterCache.getChapterInfo();
			}
			_gIsVip = G_Prg.checkVipApp();
		}
		var appEName = G_Cookie.getAppEName();
		var appENameArr = {
			'JC_EJJZS_JDGCGL':true,
			'JC_EJJZS_JSGCFG':true,
			'JC_EJJZS_JSSGGL':true
		}
		if(!appEName){
			G_Prg.alert('请先选择科目。',function(){
				location.href = '/switchMenu';
			});
			return;
		}
		
		
		$('.title').html(hrader_title);
		beitiDetail(cpt,_title,value1,value2);
	}
	init();
	/********************************************************************************
	 函数名：getTestNum
	 递归填充用户已答、错题数据等到章节列表的第一第二级
	 输入参数: data 章节json数据 userInfo 用户做题数据数组
	 返回值：returnData 当前章节用户做题数据
	 ********************************************************************************/

	/********************************************************************************
	 函数名：getUserInfo
	 功能：获取某个章节用户的做题数据信息
	 输入参数: cptID 章节ID, data 用户做题数据数组
	 ********************************************************************************/
	function _getUserInfo(cptID,data){
		var userInfo = {
			"testCount" : 0,
			"RightCount" : 0
		};
		for(var i=0;i<data.length;i++){
			if(data[i].CptID === cptID){
				userInfo.testCount = data[i].testCount;
				userInfo.RightCount = data[i].RightCount;
				break;
			}
		}
		return userInfo;
	}
	
	function _loadChapterMenu(appEName){
		var chapterData = '';
		G_AjaxApi_Record.get('/api/chapterMenu/getChapterMenuX?appEName=' + appEName, false, function(json) {
			var jsonData = JSON.parse(json);
			 if (jsonData.status === 200) {//获得有数据成功
				chapterData = jsonData.data;
			}else if(jsonData.status === 300){
				G_Prg.throw('程序运行错误！："' + jsonData.msg + '"！');
				//G_maiDian.setBugRecordInfos('程序错误','章节练习——获取章节目录',jsonData.status+':'+jsonData.msg);
			} else if(jsonData.status >= 400 && jsonData.status < 500){
				//G_maiDian.setBugRecordInfos('业务逻辑错误','章节练习——获取章节目录',jsonData.status+':'+jsonData.msg);
			} else{
				G_Prg.throw('程序运行错误！："无法处理"！');
				//G_maiDian.setBugRecordInfos('其它程序错误','章节练习——获取章节目录',jsonData.status+':'+jsonData.msg);
			}
		});
		return chapterData;
	}
	/********************************************************************************
	函数名：getChapterMenuUpdateTime
	功能：获取章节目录更新时间
	输入参数: appEName 软件英文名
	返回值：updateTime 章节目录更新时间
	********************************************************************************/
	function _getChapterMenuUpdateTime(appEName){
		var updateTime='';
		G_AjaxApi_Record.get('/api/chapterMenu/getChapterMenuUpdateTimeX?appEName=' + appEName, false, function(json) {
			var jsonData = JSON.parse(json);
			if (jsonData.status === 200) {//获得有数据成功
				updateTime = jsonData.data.ChapterMenuUpdateTime;
			}else if(jsonData.status === 300){
				G_Prg.throw('程序运行错误！："' + jsonData.msg + '"！');
				//G_maiDian.setBugRecordInfos('程序错误','章节练习——获取章节目录更新时间',jsonData.status+':'+jsonData.msg);
			} else if(jsonData.status >= 400 && jsonData.status < 500){
				//G_maiDian.setBugRecordInfos('业务逻辑错误','章节练习——获取章节目录更新时间',jsonData.status+':'+jsonData.msg);
			} else{
				G_Prg.throw('程序运行错误！："无法处理"！');
				//G_maiDian.setBugRecordInfos('其它程序错误','章节练习——获取章节目录更新时间',jsonData.status+':'+jsonData.msg);
			}
		});
		return updateTime;
	}
	/********************************************************************************
	函数名：loadChapterHistoryCptid
	功能：获得接口数据
	输入参数: userID 用户ID
	返回值：cptidData批阅过得章节
	********************************************************************************/
	function _loadChapterHistoryCptid(userID) {
		var appEName = G_Cookie.getAppEName();
		var appID = G_Cookie.getAppID();
		var arrData = '';
		if (!appEName || !userID) {
			G_Prg.throw('程序运行错误，loadChapterMenu: appEName = "' + appEName + '","userID = "' + userID + '",获取数据出现异常！');
		}
		var url = '/api/chapterMenu/getCptStatistics?appID=' + appID + '&guid=' + G_Cookie.getGuid();

		G_AjaxApi_Record.get(url, false, function (json) {
			var jsonData = JSON.parse(json);
			if (jsonData.status === 200 || jsonData.status === 201) {//获得有数据成功
				arrData = jsonData.data;
			}else if (jsonData.status === 300) {
				G_Prg.throw('程序运行错误！："' + jsonData.msg + '"！');
				//G_maiDian.setBugRecordInfos('程序错误','章节练习——获取批阅过的章节',jsonData.status+':'+jsonData.msg);
			} else if(jsonData.status >= 400 && jsonData.status < 500){
				//G_maiDian.setBugRecordInfos('业务逻辑错误','章节练习——获取批阅过的章节',jsonData.status+':'+jsonData.msg);
			} else{
				G_Prg.throw('程序运行错误！："无法处理"！');
				//G_maiDian.setBugRecordInfos('其它程序错误','章节练习——获取批阅过的章节',jsonData.status+':'+jsonData.msg);
			}
		});
		return arrData;
	}
	
		
	function beitiDetail(cptID,_title,value1,value2){
		var appID = G_Cookie.getAppID();
		var callback = function(){
			beiti();
		}
		var _data = getTestFromCache(cptID);
		var info = _data.info;
		var m = getTestFromServer(cptID, appID, callback);
		var data = JSON.parse(m.test);
		$('.dati').html('做题模式');
		$('.dati').attr('value',4);
		$('.dati').css('display','none');
		
		$('.content').html('');
		var beitiStr = '<ul class="beiti_list"></ul>';
		$('.content').html(beitiStr);
		var strTitle = '';
		var num = 0;
		var _data = G_SetTestInfo.replaceImgURL(data);
		$('#loadingDiv').css('display','none');
		for(var i = 0; i < _data.StyleItems.length; i ++){
			var title = '';
			var explain = '';
			var answer = '';
			if(_data.StyleItems[i].Type == 'ATEST'){ // 单选
				var n = _data.StyleItems[i].TestItems;
				for(var j = 0;j < n.length; j ++){
					title = n[j].Title; // 题目
					if(n[j].Explain){
						explain = '<div class="jie_da"><span class="da">解</span><p>'+data.StyleItems[i].TestItems[j].Explain+'</p></div>';
					}else{
						explain = '';
					} 
					for(var k = 0; k < n[j].SelectedItems.length; k++){
						if(n[j].SelectedItems[k].ItemName == n[j].Answer){
							var index = k;
							answer = _data.StyleItems[i].TestItems[j].SelectedItems[index].Content;
		
						}
					}
					strTitle = '<li class="exam_list" data-display="none">'+
						'<div class="problme_title"><span>'+ (num+j+1) + '.' + title + '</span>'+ '</div>'+
						'<div class="problme_key"><div class="jie_da"><span class="da">答</span>'+
						'<p>' + answer + '</p></div>'+ explain + '</div></li>'
					$('.beiti_list').append(strTitle);
					display_none();
					//_clickEvent();
					myscroll.refresh();
				}
				num = num + n.length;
			}else if(_data.StyleItems[i].Type == 'A3TEST'){  //案例分析题
				var n = _data.StyleItems[i].TestItems;
				for(var j = 0;j < n.length; j ++){
					title = n[j].FrontTitle; // 题目
					if(n[j].Explain){
						explain = '<div class="jie_da"><span class="da">解</span><p>'+_data.StyleItems[i].TestItems[j].Explain+'</p></div>';
					}else{
						explain = '';
					}
					var title1 = '';
					var answer1 = '';
					// 主题干下面的小题干；
					for(var k = 0; k < n[j].A3TestItems.length; k++){
						title1 += '<br/><span>(' + (k+1)+')'+ n[j].A3TestItems[k].Title + '</span>';
						var m = n[j].A3TestItems[k].Answer.split('');
						var _answer = '';
						for(var q = 0; q < m.length; q ++){
							for(var s = 0; s < n[j].A3TestItems[k].SelectedItems.length; s++){
								if(m[q] == n[j].A3TestItems[k].SelectedItems[s].ItemName){
									_answer += n[j].A3TestItems[k].SelectedItems[s].Content + ' ';
								}
							}
						}
						answer1 += '<span>(' + (k+1)+')'+ _answer + '</span><br/>';
					}
					strTitle = '<li class="exam_list" data-display="none">'+
						'<div class="problme_title"><span>'+ (num+j+1) + '.' + title + '</span>'+ title1 +'</div>'+
						'<div class="problme_key"><div class="jie_da"><span class="da">答</span>'+
						'<p>' + answer1 + '</p></div>'+ explain + '</div></li>'
					$('.beiti_list').append(strTitle);
					myscroll.refresh();
					display_none();
					//_clickEvent();
				}
				num = num + n.length;
			} else if(_data.StyleItems[i].Type == 'XTEST'){
				var n = _data.StyleItems[i].TestItems;
				for(var j = 0;j < n.length; j ++){
					var imgUrl = '';// 是否收藏图片的路径
					title = n[j].Title; // 题目
				
					if(n[j].Explain){
						explain = '<div class="jie_da"><span class="da">解</span><p>'+_data.StyleItems[i].TestItems[j].Explain+'</p></div>';
					}else{
						explain = '';
					}
			
					var answer1 = '';
					var answer = n[j].Answer.split('');
					// 主题干下面的小题干；
					for(var s = 0; s < answer.length; s ++){
						for(var k = 0; k < n[j].SelectedItems.length; k++){
							if(answer[s] == n[j].SelectedItems[k].ItemName){
								answer1 += n[j].SelectedItems[k].Content;
								break;
							}
						}
					}
					
					strTitle = '<li class="exam_list" data-display="none">'+
						'<div class="problme_title"><span>'+ (num+j+1) + '.' + title + '</span></div>'+
						'<div class="problme_key"><div class="jie_da"><span class="da">答</span>'+
						'<p>' + answer1 + '</p></div>'+ explain + '</div></li>'
					$('.beiti_list').append(strTitle);
					myscroll.refresh();
					display_none();
					//_clickEvent();
				}
				num = num + n.length;
			}else if(_data.StyleItems[i].Type == 'BTEST'){
				var n = _data.StyleItems[i].TestItems;
				for(var j = 0;j < n.length; j ++){
					var k = n[j].BTestItems;
					var _answer = n[j].SelectedItems;
					for(var l = 0; l < k.length; l ++){
						title = k[l].Title; // 题目
				
						if(k[l].Explain){
							explain = '<div class="jie_da"><span class="da">解</span><p>'+_data.StyleItems[i].TestItems[j].Explain+'</p></div>';
						}else{
							explain = '';
						}
						// ? 答案未定
						var answer_m = k[l].Answer;
						var answer1 = '';
						for(var s = 0; s < _answer.length; s++){
							if(answer_m == _answer[s].ItemName){
								answer1 = _answer[s].Content;
							}
						}
						
						strTitle = '<li class="exam_list" data-display="none">'+
							'<div class="problme_title"><span>'+ (num+l+1) + '.' + title + '</span></div>'+
							'<div class="problme_key"><div class="jie_da"><span class="da">答</span>'+
							'<p>' + answer1 + '</p></div>'+ explain + '</div></li>'
						$('.beiti_list').append(strTitle);
						display_none();
						myscroll.refresh();
						//_clickEvent();
					}
					num = num + k.length;
				}	
			}else if(_data.StyleItems[i].Type == 'JDTEST' || _data.StyleItems[i].Type == 'PDTEST' || _data.StyleItems[i].Type == 'TKTEST'){
				var n = _data.StyleItems[i].TestItems;
				for(var j = 0;j < n.length; j ++){
					title = n[j].Title; // 题目
				
					if(n[j].Explain){
						explain = '<div class="jie_da"><span class="da">解</span><p>'+_data.StyleItems[i].TestItems[j].Explain+'</p></div>';
					}else{
						explain = '';
					}
					// ? 答案未定
					var answer1 = n[j].Answer;
					
					strTitle = '<li class="exam_list" data-display="none">'+
						'<div class="problme_title"><span>'+ (num+j+1) + '.' + title + '</span></div>'+
						'<div class="problme_key"><div class="jie_da"><span class="da">答</span>'+
						'<p>' + answer1 + '</p></div>'+ explain + '</div></li>'
					$('.beiti_list').append(strTitle);
					display_none();
					myscroll.refresh();
					//_clickEvent();
				}
				num = num + n.length;
			}
			myscroll.refresh();
		}
			
		$('.back').click(function(){
			window.location.href = '/chapterBeiti?fromUrl=beiti&value1='+ value1 + '&value2=' + value2 + '&title=' + _title;
		});
		
	}
		
	// 截取网址上传递的参数	
	function GetQueryString(name) {  
	    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");  
	    var r = window.location.search.substr(1).match(reg);  //获取url中"?"符后的字符串并正则匹配
	    var context = "";  
	    if (r != null)  
	         context = r[2];  
	    reg = null;  
	    r = null;  
	    return context == null || context == "" || context == "undefined" ? "" : context;  
	}
	
	
	
	 function getTestFromServer(cptID, appID, callback){
	 	var data = '';
        var URL = '/api/exam/getChapterTestPlus';
        var params = {
        	appID:appID,
        	cptID:cptID,
        	queryHistory:1,
        	queryTestInfo:1,
        	queryKnowledge:1,
//      	userID:G_Cookie.getUserID(),
//      	userName:G_Cookie.getUserName(),
        	guid:G_Cookie.getGuid()
        }
        var success = function (json) {
            var jsonObj = JSON.parse(json);
            if (jsonObj.status === 200) {	//200 获取数据成功
               data = jsonObj.data;
            } else if (jsonObj.status === 201) {	//201 没有数据；
                G_Prg.throw('程序运行错误，没有您要查找的试题数据！', callback);
            } else if (jsonObj.status === 300) {	//300 连接数据库失败
                //G_maiDian.setBugRecordInfos('程序错误', '做题页面——获取章节练习试题', jsonObj.status + ':' + jsonObj.msg);
                G_Prg.throw('程序运行错误，TestData._getAllTestJSON,数据库获取数据异常');
            } else if (jsonObj.status >= 400 && jsonObj.status < 500) {
                //G_maiDian.setBugRecordInfos('业务逻辑错误', '做题页面——获取章节练习试题', jsonObj.status + ':' + jsonObj.msg);
            } else {
                //G_maiDian.setBugRecordInfos('其它程序错误', '做题页面——获取章节练习试题', jsonObj.status + ':' + jsonObj.msg);
                G_Prg.throw('不能处理，TestData._getAllTestJSON:status=' + jsonObj.status);
            }
        };
        G_AjaxApi_Record.post(URL, params, false, success);
        return data;
    }
	
	
       
	// 获取题目信息
	function getTestFromCache(cptID){
		var data = '';
            var params = {
            	appID:G_Cookie.getAppID(),
            	cptID:cptID,
            	userID:G_Cookie.getUserID(),
            	userName:G_Cookie.getUserName(),
            	guid:G_Cookie.getGuid()
            }
            var URL = '/api/exam/getChapterTestInfoX?guid='+G_Cookie.getGuid()+'&&appID='+G_Cookie.getAppID()+'&&cptID='+cptID;
            var success = function (json) {
                var jsonObj = JSON.parse(json);
                if (jsonObj.status === 200) {	//200 获取数据成功
                   data = jsonObj.data;
                } else if (jsonObj.status === 300) {	//300 连接数据库失败
                    //G_maiDian.setBugRecordInfos('程序错误', '做题页面——获取用户做题数据info包', jsonObj.status + ':' + jsonObj.msg);
                    G_Prg.throw('程序运行错误，TestData._getAllTestJSON,数据库获取数据异常');
                } else if (jsonObj.status >= 400 && jsonObj.status < 500) {
                    //G_maiDian.setBugRecordInfos('业务逻辑错误', '做题页面——获取用户做题数据info包', jsonObj.status + ':' + jsonObj.msg);
                } else {
                   // G_maiDian.setBugRecordInfos('其它程序错误', '做题页面——获取用户做题数据info包', jsonObj.status + ':' + jsonObj.msg);
                    G_Prg.throw('不能处理，TestData._getAllTestJSON:status=' + jsonObj.status);
                }
            };
            G_AjaxApi_Record.get(URL, true, success);
			return data;
        }

	
	/********************************************************************************
	函数名：iOSreturn
	功能：苹果商店功能
	输入参数: 无
	返回值：无
	*******************************************************************************/
	function iOSreturn(){
	    var username=G_Cookie.getUserID();
	    var softname=G_Cookie.getAppEName();
	    var answer=username+"/"+softname;
	    return answer;
	}
	
	// 背题模式
	function display_none(){
		var arr = [];
		function getAttr(){
			for(var i = 0; i < $('.exam_list').length; i ++){
				arr[i] = $('.exam_list').eq(i).attr('data-display');
			}
		}
		getAttr();
		$(".exam_list").on("click", function() {
			var index = $(this).index();
			if (arr[index] == 'none') {
				$(this).find('.problme_title').siblings().css('display','block');
				$(this).attr('data-display', 'block');
				arr[index] = $(this).attr('data-display');
				//$(this).siblings().find('.problme_title').siblings().css("display", "none");
			}else{
				$(this).find('.problme_title').siblings().css('display','none');
				$(this).attr('data-display', 'none');
				arr[index] = $(this).attr('data-display');
				//$(this).siblings().find('.problme_title').siblings().css("display", "none");
			}
			myscroll.refresh();
		})	
	}
});

	



	
